package com.ddl.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisService {

    private static Logger log = LoggerFactory.getLogger(RedisService.class);

    @Resource
    private RedisTemplate redisTemplate;

    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    public String get(final String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            log.error("redis set方法异常", e);
            throw e;
        }
        return result;
    }

    public boolean expire(final String key, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            log.error("redis expire方法异常", e);
            throw e;
        }
        return result;
    }

    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;

        try {
            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            log.error("redis set方法异常", e);
            throw e;
        }
        return result;
    }

    public Long lpush(String key, String value) {
        Long length = redisTemplate.opsForList().leftPush(key, value);
        return length;
    }
}
